package org.edu.modules.oa.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.catalina.connector.Request;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.oa.config.HttpURLConnectionUtil;
import org.edu.modules.oa.entity.*;
import org.edu.modules.oa.entity.bo.BasicResponseBO;
import org.edu.modules.oa.mapper.IVeOaCarInfoMapper;
import org.edu.modules.oa.mapper.IVeOaDiaryMapper;
import org.edu.modules.oa.service.IVeOaDiaryService;
import org.edu.modules.oa.vo.VeOaDiaryTableVo;
import org.edu.modules.oa.vo.VeOaMeetCheckTableVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service

public class VeOaDiaryServiceImpl extends ServiceImpl<IVeOaDiaryMapper, VeOaDiaryEntity> implements IVeOaDiaryService {
    @Value("${common.host}")
    private String dirHost;

    @Autowired
    ObjectMapper mapper;

    @Resource
    private IVeOaDiaryMapper iVeOaDiaryMapper;

    @Override
    public HashMap<String, Object> showTable(String themeList, VeOaDiaryEntity veOaDiaryEntity, Integer startPage, Integer pageSize) {
        // 调用mybatisplus的分页
        IPage<VeOaDiaryEntity> page = new Page<>(startPage, pageSize);
        // 拼接查询条件
        QueryWrapper<VeOaDiaryEntity> tableWrapper = new QueryWrapper<>();
        if (veOaDiaryEntity.getCreateBy() != null && veOaDiaryEntity.getCreateBy() != "%%") {
            tableWrapper.like("create_by", veOaDiaryEntity.getCreateBy());

        }
        if (veOaDiaryEntity.getRijiType() != null && veOaDiaryEntity.getRijiType() != "%%") {
            tableWrapper.like("riji_type", veOaDiaryEntity.getRijiType());

        }
        if (!themeList.equals("")) {
            String[] theme = themeList.split(",");
            for (int i = 0; i < theme.length; i++) {
                if (i == 0) {
                    tableWrapper.and(wrapper -> wrapper.like("title_str", theme[0]));
                } else {
                    tableWrapper.or().like("title_str", theme[i]);
                }
            }
        }
        tableWrapper.orderByDesc("create_time");
        // 条件加上分页查询
        page = iVeOaDiaryMapper.selectPage(page, tableWrapper);
        List<VeOaDiaryEntity> entityList = page.getRecords();


        int count = iVeOaDiaryMapper.selectCount(tableWrapper);
        // 把查出来的东西存到map里面去
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", entityList);
        map.put("count", count);

        // 查询表格总行数
        return map;
    }

    @Override
    public HashMap<String, Object> selectTheme(VeOaDiaryEntity veOaDiaryEntity, Integer startPage, Integer pageSize) {
        // 调用mybatisplus的分页
        IPage<VeOaDiaryEntity> page = new Page<>(startPage, pageSize);
        // 拼接查询条件
        QueryWrapper<VeOaDiaryEntity> tableWrapper = new QueryWrapper<>();
        if (veOaDiaryEntity.getTitleStr() != null && veOaDiaryEntity.getTitleStr() != "%%") {
            tableWrapper.like("title_str", veOaDiaryEntity.getTitleStr());

        }
        tableWrapper.select("distinct title_str");
        page = iVeOaDiaryMapper.selectPage(page, tableWrapper);
        List<VeOaDiaryEntity> entityList = page.getRecords();


        int count = iVeOaDiaryMapper.selectCount(tableWrapper);
        // 把查出来的东西存到map里面去
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", entityList);
        map.put("count", count);

        // 查询表格总行数
        return map;
    }

    @Override
    public List<VeOaDiaryEntity> selectType() {
        // 拼接查询条件
        QueryWrapper<VeOaDiaryEntity> tableWrapper = new QueryWrapper<>();
        tableWrapper.select("distinct riji_type");
        List<VeOaDiaryEntity> typeList = iVeOaDiaryMapper.selectList(tableWrapper);
        return typeList;
    }

    @Override
    public Integer addDiary(VeOaDiaryEntity veOaAddDiaryEntity) {
        VeOaDiaryEntity veOaDiaryEntity = new VeOaDiaryEntity();
        veOaDiaryEntity.setTitleStr(veOaAddDiaryEntity.getTitleStr());
        veOaDiaryEntity.setRijiType(veOaAddDiaryEntity.getRijiType());
        veOaDiaryEntity.setRijiContent(veOaAddDiaryEntity.getRijiContent());
        // 获取redis存的用户值
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veOaDiaryEntity.setCreateBy(user.getId());
        veOaDiaryEntity.setCreateTime(new Date());
        veOaDiaryEntity.setIsDeleted(0);
        veOaDiaryEntity.setTerminalId(0);
        Integer countMeet = iVeOaDiaryMapper.insert(veOaDiaryEntity);
        return null;
    }

    @Override
    public Integer deleteWorkDiary(Integer id) {
        int result = iVeOaDiaryMapper.deleteById(id);
        return result;
    }

    @Override
    public Integer editWorkDiary(VeOaDiaryEntity veOaDiaryEntity) {
        int result = iVeOaDiaryMapper.updateById(veOaDiaryEntity);
        return result;
    }

    @Override
    public HashMap<String, Object> showVoTable(String themeList, VeOaDiaryEntity veOaDiaryEntity, Integer startPage, Integer pageSize) {
        String[] s = null;
        if (themeList != null) {
            s = themeList.split(",");
        }
        List<VeOaDiaryEntity> voList = iVeOaDiaryMapper.showVoTable(veOaDiaryEntity, (startPage - 1) * pageSize, pageSize, s);
//        List<VeOaDiaryTableVo> list = new ArrayList<>();
//        String userUrl = "/common/veCommon/getAppUserBySearch?interfaceUserId=09d5e1e7f9b049008eee645c783a1d67";
//        BasicResponseBO<List> result = getUrl(userUrl, List.class);
//        BasicResponseBO<List<VeBaseUserEntity>> userList = new BasicResponseBO<>();
//        userList.setSuccess(result.getSuccess()).setMessage(result.getMessage())
//                .setResult(result.getResult() == null ? null :
//                        JSON.parseArray(JSON.toJSONString(result.getResult()), VeBaseUserEntity.class));
//        List<VeBaseUserEntity> users = new ArrayList<>();
//        for (int j = 0; j < userList.getResult().size(); j++) {
//            String userInfo = "/common/veCommon/queryAppUserByUserId?interfaceUserId=09d5e1e7f9b049008eee645c783a1d67&userId=" + userList.getResult().get(j).getUserId();
//            BasicResponseBO<VeBaseUserEntity> info = getUrl(userInfo, VeBaseUserEntity.class);
//            VeBaseUserEntity user = new VeBaseUserEntity();
//            user.setId(info.getResult().getId());
//            user.setRealName(info.getResult().getRealName());
//            user.setUserId(info.getResult().getUserId());
//            user.setUsername(info.getResult().getUsername());
//            users.add(user);
//        }
//        for (int i = 0; i < voList.size(); i++) {
//            VeOaDiaryTableVo veOaDiaryTableVo = new VeOaDiaryTableVo();
//            for (int j = 0; j < users.size(); j++) {
//                if (users.get(j).getId().equals(voList.get(i).getCreateBy())) {
//                    veOaDiaryTableVo.setRealname(users.get(j).getRealName());
//                    break;
//                }
//            }
//            veOaDiaryTableVo.setId(voList.get(i).getId());
//            veOaDiaryTableVo.setCreateBy(voList.get(i).getCreateBy());
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String date = sdf.format(voList.get(i).getCreateTime());
//            veOaDiaryTableVo.setCreateTime(date);
//            veOaDiaryTableVo.setRijiContent(voList.get(i).getRijiContent());
//            veOaDiaryTableVo.setRijiType(voList.get(i).getRijiType());
//            veOaDiaryTableVo.setTitleStr(voList.get(i).getTitleStr());
//            veOaDiaryTableVo.setUpdateTime(voList.get(i).getUpdateTime().toString());
//            list.add(veOaDiaryTableVo);
//        }
        Integer count = iVeOaDiaryMapper.tableCount(veOaDiaryEntity, s);
        // 把查出来的东西存到map里面去
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", voList);
        map.put("count", count);
        // 查询表格总行数
        return map;
    }

    @Override
    public List<VeOaDiaryTableVo> showExcel() {
        List<VeOaDiaryTableVo> voList = iVeOaDiaryMapper.showExcel();
        String userUrl = "/common/veCommon/getAppUserBySearch?interfaceUserId=09d5e1e7f9b049008eee645c783a1d67";
        BasicResponseBO<List> result = getUrl(userUrl, List.class);
        BasicResponseBO<List<VeBaseUserEntity>> userList = new BasicResponseBO<>();
        userList.setSuccess(result.getSuccess()).setMessage(result.getMessage())
                .setResult(result.getResult() == null ? null :
                        JSON.parseArray(JSON.toJSONString(result.getResult()), VeBaseUserEntity.class));
        List<VeBaseUserEntity> users = new ArrayList<>();
        for (int i = 0; i < userList.getResult().size(); i++) {
            String userInfo = "/common/veCommon/queryAppUserByUserId?interfaceUserId=09d5e1e7f9b049008eee645c783a1d67&userId=" + userList.getResult().get(i).getUserId();
            BasicResponseBO<VeBaseUserEntity> info = getUrl(userInfo, VeBaseUserEntity.class);
            VeBaseUserEntity user = new VeBaseUserEntity();
            user.setId(info.getResult().getId());
            user.setRealName(info.getResult().getRealName());
            user.setUserId(info.getResult().getUserId());
            user.setUsername(info.getResult().getUsername());
            users.add(user);
        }
        for (VeOaDiaryTableVo veOaDiaryTableVo : voList){
            veOaDiaryTableVo.getCreateBy();
            for (int i = 0;i<users.size();i++){
                if (veOaDiaryTableVo.getCreateBy().equals(users.get(i).getId())){
                    veOaDiaryTableVo.setCreateBy(users.get(i).getRealName());
                    break;
                }
            }
        }
        return voList;
    }

    /**
     * 调用公告数据接口
     */
    private <T> BasicResponseBO<T> getUrl(String url, Class<T> clazz) {
        try {
            url = dirHost + url;
            String result = HttpURLConnectionUtil.doGet(url);
            BasicResponseBO<T> re = mapper.readValue(result, new TypeReference<BasicResponseBO<T>>() {
            });
            T body = mapper.readValue(mapper.writeValueAsString(re.getResult()), clazz);
            re.setResult(body);
            return re;
        } catch (Exception e) {
            return new BasicResponseBO<T>().setSuccess(false).setMessage("操作失败");
        }
    }
}
